package com.shark.security.jwt.persistent.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.shark.security.jwt.persistent.entity.PermissionInfoEntity;

@Repository
public class PermissionRepository {

	@Autowired
	private NamedParameterJdbcTemplate jdbcTemplate;
	
	private static final String SQL_GET_PERMISSION_BY_ID = "select id, name, url, permission, remark, p_id, type, method from t_sys_permission_info where id in (:lisPermisionId)";
	
	private static final String SQL_GET_PERMISSION_BY_LOGIN_NAME = "select distinct t1.id, t1.name, t1.url, t1.permission, t1.remark, t1.p_id, t1.type, t1.method from t_sys_permission_info t1 " +
			"join t_sys_role_permission t2 on t1.id = t2.permission_id " +
			"join t_sys_role t3 on t3.id = t2.role_id and t3.flag = 0 " +
			"join t_sys_user_role t4 on t3.id = t4.role_id " +
			"join t_sys_user t5 on t5.id = t4.user_id and t5.flag = 0 and t5.login_name = :loginName";
	/**
	 * 
	 * @param lisPermisionId
	 * @return
	 */
	public List<PermissionInfoEntity> getPermissonByRole(List<Integer> lisPermisionId) {
		Map<String, Object> mapParam = new HashMap<>();
		mapParam.put("lisPermisionId", lisPermisionId);
		
		return jdbcTemplate.query(SQL_GET_PERMISSION_BY_ID, mapParam, new RowMapper<PermissionInfoEntity>() {

			@Override
			public PermissionInfoEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
				PermissionInfoEntity u = new PermissionInfoEntity();
				u.setId(rs.getInt("id"));
				u.setName(rs.getString("name"));
				u.setUrl(rs.getString("url"));
				u.setPermission(rs.getString("permission"));
				u.setRemark(rs.getString("remark"));
				u.setpId(rs.getInt("p_id"));
				u.setType(rs.getByte("type"));
				u.setMethod(rs.getString("method"));
				return u;
			}
		
		});
	}
	/**
	 * 
	 * @param lisPermisionId
	 * @return
	 */
	public List<PermissionInfoEntity> getPermissonByLoginName(String loginName) {
		Map<String, Object> mapParam = new HashMap<>();
		mapParam.put("loginName", loginName);
		
		return jdbcTemplate.query(SQL_GET_PERMISSION_BY_LOGIN_NAME, mapParam, new RowMapper<PermissionInfoEntity>() {

			@Override
			public PermissionInfoEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
				PermissionInfoEntity u = new PermissionInfoEntity();
				u.setId(rs.getInt("id"));
				u.setName(rs.getString("name"));
				u.setUrl(rs.getString("url"));
				u.setPermission(rs.getString("permission"));
				u.setRemark(rs.getString("remark"));
				u.setpId(rs.getInt("p_id"));
				u.setType(rs.getByte("type"));
				u.setMethod(rs.getString("method"));
				return u;
			}
		
		});
	}
}
